package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : [wangtao]
 * @className : LoginFilter
 * @description : [登录控制过滤器]
 * @createTime : [2022/10/7 12:53]
 * @updateTime : [2022/10/7 12:53]
 */
//@RestControllerAdvice
@Slf4j
@WebFilter(filterName = "loginfilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String[] str = {"/backend/**", "/front/**", "/employee/login", "/employee/logout","/user/sendMsg","/user/login",  "/common/**",};
        // * A. 获取本次请求的URI
        String requestURI = request.getRequestURI();
//        log.info("ssas{}",requestURI);
/**
 * A. 获取本次请求的URI
 *
 * B. 判断本次请求, 是否需要登录, 才可以访问
 *
 * C. 如果不需要，则直接放行
 *
 * D. 判断登录状态，如果已登录，则直接放行
 *
 * E. 如果未登录, 则返回未登录结果
 */

        /*
         *  后台 已登录用户过滤掉
         */
        if (request.getSession().getAttribute("employee") != null) {
          Long employee = (long)request.getSession().getAttribute("employee");
            log.info("用户已登录 {}", employee);
            BaseContext.setCurrentId(employee);
            chain.doFilter(request, response);
            return;
        }

/*
 * @author wangtao
 * @description  前台 过滤代码
 * @createTime  2022/10/13 12:59
 */
        if (request.getSession().getAttribute("userId") != null) {
            Long userId = (long)request.getSession().getAttribute("userId");
            log.info("用户已登录 {}", userId);
            BaseContext.setCurrentId(userId);
            chain.doFilter(request, response);
            return;
        }





        /*
         *过滤静态资源
         */
        boolean flog = method(str, requestURI);
        if (flog) {
            chain.doFilter(request, response);
            return;
        }
            log.info("用户未登录");
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
    }
    private boolean method(String[] str, String requestURI) {
        AntPathMatcher ant = new AntPathMatcher();
        for (String s : str) {
            if (ant.match(s, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
